/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.bizentity.json.increment;

import com.fasterxml.jackson.core.JsonGenerator;
import com.inspur.edp.bef.bizentity.common.BizEntityJsonConst;
import com.inspur.edp.bef.bizentity.increment.BizEntityIncrement;
import com.inspur.edp.bef.bizentity.increment.entity.action.MgrActionIncrement;
import com.inspur.edp.cef.designtime.api.json.CefNames;
import com.inspur.edp.cef.designtime.api.json.SerializerUtils;
import com.inspur.edp.das.commonmodel.entity.increment.CommonModelIncrement;
import com.inspur.edp.das.commonmodel.json.increment.CommonModelIncrementSerializer;
import com.inspur.edp.das.commonmodel.json.increment.CommonObjectIncrementSerializer;
import java.io.IOException;
import java.util.HashMap;
import lombok.var;

public class BizEntityIncrementSerializer extends CommonModelIncrementSerializer {

  @Override
  protected CommonObjectIncrementSerializer getObjectIncrementSerializer() {
    return new BizObjectIncrementSerializer();
  }

  @Override
  protected void writeExtendInfo(CommonModelIncrement value, JsonGenerator gen) {
    BizEntityIncrement increment = (BizEntityIncrement) value;
    writeMgrActions(increment.getActions(), gen);
  }


  private void writeMgrActions(HashMap<String, MgrActionIncrement> actions, JsonGenerator gen) {
    if (actions == null) {
      return;
    }
    SerializerUtils.writePropertyName(gen, BizEntityJsonConst.BizMgrActions);
    SerializerUtils.WriteStartArray(gen);
    for (var item : actions.entrySet()) {
      try {
        SerializerUtils.writeStartObject(gen);
        SerializerUtils.writePropertyValue(gen, CefNames.Id, item.getKey());

        SerializerUtils.writePropertyName(gen, BizEntityJsonConst.BizMgrAction);
        MgrActionIncrementSerializer serializer = new MgrActionIncrementSerializer();
        serializer.serialize(item.getValue(), gen, null);
        SerializerUtils.writeEndObject(gen);
      } catch (IOException e) {
        throw new RuntimeException("Be动作增量序列化失败", e);
      }
    }
    SerializerUtils.WriteEndArray(gen);
  }
}
